import {app, BrowserWindow} from "electron";
import {updater} from "../services/HotUpdater";
import {updater as updaterTest} from "../services/HotUpdaterTest";
import Update from "../services/checkUpdate";
import {UpdateStatus} from "electron_updater_node_core";
import {IpcChannel, IpcMainHandle} from "../ipc";

const ALL_UPDATER = new Update();

export function useUpdateHandle(): Pick<
	IpcMainHandle,
	| IpcChannel.CheckUpdate
	| IpcChannel.ConfirmUpdate
	| IpcChannel.HotUpdate
	| IpcChannel.HotUpdateTest
> {
	return {
		[IpcChannel.CheckUpdate]: (event) => {
			ALL_UPDATER.checkUpdate(BrowserWindow.fromWebContents(event.sender));
		},
		[IpcChannel.ConfirmUpdate]: () => {
			ALL_UPDATER.quitAndInstall();
		},
		[IpcChannel.HotUpdate]: (event) => {
			updater(BrowserWindow.fromWebContents(event.sender));
		},
		[IpcChannel.HotUpdateTest]: async (event, arg) => {
			console.log("hot-update-test");
			try {
				let updateInfo = await updaterTest(
					BrowserWindow.fromWebContents(event.sender)
				);
				if (updateInfo === UpdateStatus.Success) {
					app.quit();
				} else if (updateInfo === UpdateStatus.HaveNothingUpdate) {
					console.log("不需要更新");
				} else if (updateInfo === UpdateStatus.Failed) {
					console.error("更新出错");
				}
			} catch (error) {
				// 更新出错
				console.error("更新出错");
			}
		},
	};
}
